package com.dwxt.cdms.service;

import com.alibaba.fastjson.JSON;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.*;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.entity.vo.YeYingVO;
import com.dwxt.cdms.entity.yeying.YeYingData;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.cdms.view.EquipmentCustomView;
import com.dwxt.cdms.vo.SelectEquipmentCustomVo;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.IDUtils;
import com.dwxt.common.util.JsonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class YeYingDataService {

    @Autowired
    private YeYingDataMapper yeYingDataMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private EquipmentCustomMapper equipmentCustomMapper;

    @Autowired
    private StationService stationService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private WarningMapper warningMapper;
    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;
    @Autowired
    private RelationService relationService;

    public Map receiveData(YeYingVO yeYingVO) {
        log.info("当前人数："+yeYingVO.getPeopleNumber());
        if (yeYingVO.getPeopleSataus().equals(1)) {
            log.error("摔倒");
        } else if (yeYingVO.getPeopleSataus().equals(2)) {
            log.error("预警");
        } else {
            log.info("正常");
        }
        log.info("接收到夜莺数据："+yeYingVO.toString());
        HashMap<String, String> map = new HashMap<>();
        map.put("command", "setEmergencyInfo");
        Equipment equipment = equipmentMapper.selectEquipmentBySerialNumber(yeYingVO.getDeviceId(), null);
        if (equipment == null) {
            log.error("接收夜莺数据失败，系统中不存在该设备。失败信息："+yeYingVO.toString());
            //return BaseResult.build(StatusCode.DEVICE_NOT_EXIST);
            return map;
        }
        EquipmentCustom equipmentCustom = equipmentCustomMapper.selectByEquipmentId(equipment.getId());
        if (equipmentCustom == null) {
            log.error("接收夜莺数据失败，该设备未绑定。失败信息："+yeYingVO.toString());
            //return BaseResult.build(StatusCode.NOT_BIND_EQUIPMENT);
            return map;
        }
        YeYingData yeYingData = new YeYingData();
        BeanUtils.copyProperties(yeYingVO,yeYingData);
        yeYingData.setPeoplehealth(JSON.toJSONString(yeYingVO.getPeoplehealth()));
        yeYingData.setCustomerId(equipmentCustom.getCustomerId());
        yeYingData.setCreate_time(new Date());
        //存入redis
        RedisUtil.set(yeYingData.getDeviceId(), yeYingData);
        //返回紧急联系电话，用于呼叫
        Customer customer = customerMapper.selectByPrimaryKey(equipmentCustom.getCustomerId());
        if (customer != null && StringUtils.isNotBlank(customer.getCallContact())&&customer.getCallContact().equals("1")&& StringUtils.isNotBlank(customer.getContactPhone())) {
            map.put("phone", customer.getContactPhone());
        }
        log.error(JSON.toJSONString(map));
        //未跌倒，不入库
        if (!yeYingVO.getPeopleSataus().equals(1)) {
            //return BaseResult.ok();
            return map;
        }
        int i = yeYingDataMapper.insertSelective(yeYingData);
        //预警
        insertWarning(equipment,customer);
        sendMessage(customer);
        return map;
    }

    public void sendMessage(Customer customer) {
        HealthMessage msg = new HealthMessage();
        msg.setType("跌倒报警");
        StringBuilder sb = new StringBuilder();
        sb.append("【").append(customer.getName()).append("】跌倒报警，请您注意！");
        msg.setContent(sb.toString());
        List<Customer> customers = relationService.selectMyRelationCustomer(customer.getId());
        for (Customer customer1 : customers) {
            msg.setCustomerId(customer1.getId());
            msg.setId(UUID.randomUUID().toString());
            healthWarnRecordMapper.insertMessage(msg);
        }

    }

    private void insertWarning(Equipment equipment, Customer customer) {
        Warning warning = new Warning();
        warning.setId(IDUtils.genItemId());
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateFormat.format(new Date());
        warning.setWarningTime(dateStr);
        StringBuilder sb = new StringBuilder();
        sb.append("【").append(customer.getName()).append("】跌倒报警，请您注意！");
        warning.setContent(sb.toString());
        warning.setCustomerId(customer.getId());
        warning.setType("60");
        warning.setState("0");
        warning.setImei(equipment.getSerialNumber());
        warning.setCategory(equipment.getCategory());
        warningMapper.insertSelective(warning);
    }


    public BaseResult selectYeYingDataPageGroup(Page page, String name) {
        Integer stationId = stationService.getLoginUserStation();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<YeYingData> yeYingDataList = yeYingDataMapper.selectYeYingDataPageGroup(name, stationId);
        List<YeYingVO> voList = yeYingDataList.stream().map(yeYingData -> entity2VO(yeYingData)).collect(Collectors.toList());
        PageInfo<YeYingVO> pageInfo = new PageInfo<>(voList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult selectYeYingDataPage(Page page, Integer customerId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<YeYingData> yeYingDataList = yeYingDataMapper.selectPageByCustomerId(customerId);
        List<YeYingVO> voList = yeYingDataList.stream().map(yeYingData -> {
            return entity2VO(yeYingData);
        }).collect(Collectors.toList());
        PageInfo<YeYingVO> pageInfo = new PageInfo<>(voList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult selectYeYingDataById(Integer id) {
        YeYingVO vo =entity2VO(yeYingDataMapper.selectYeYingDataById(id));
        return BaseResult.ok(vo);
    }

    public YeYingVO entity2VO(YeYingData yeYingData) {
        YeYingVO vo = new YeYingVO();
        BeanUtils.copyProperties(yeYingData, vo);
        vo.setPeoplehealth(JSON.parseArray(yeYingData.getPeoplehealth()));
        return vo;
    }

    public BaseResult selectYeYingFromRedisById(Integer customerId) {
        SelectEquipmentCustomVo vo = new SelectEquipmentCustomVo();
        vo.setCustomerId(customerId);
        List<EquipmentCustomView> list = equipmentCustomMapper.selectEquipmentCustomList(vo);
        for (EquipmentCustomView equipmentCustomView : list) {
            if (equipmentCustomView.getCategory().equals("11")) {
                YeYingData yeYingData = RedisUtil.get(equipmentCustomView.getSerialNumber(), YeYingData.class);
                Map<String, Object> map = new HashMap<>();
                if (yeYingData != null) {
                    map = JsonUtils.jsonToPojo(JsonUtils.objectToJson(yeYingData), Map.class);
                }
                Customer customer = customerMapper.selectByPrimaryKey(equipmentCustomView.getCustomerId());
                map.put("contactName", customer.getContactName());
                map.put("contactPhone", customer.getContactPhone());
                map.put("callContact", customer.getCallContact()==null?"0":"1");
                return BaseResult.ok(map);
            }
        }
        return BaseResult.build(StatusCode.NOT_BIND_EQUIPMENT);
    }
}
